
#import "PUCategoryVC.h"
#import "PUFoodDetailsVC.h"
#import "PUHomeCell.h"
#import "JXCategoryView.h"
#import "PUData.h"
#import "PUFoodsModel.h"
#import "PUPhoneLogin.h"
#define kBaseSegmentHeight 40.0f

@interface PUCategoryVC ()<UICollectionViewDelegate,UICollectionViewDataSource,XLHomeCellCellDelegate,JXCategoryViewDelegate>
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, retain) NSMutableArray *recommendData;
@property (nonatomic, retain) NSMutableArray *taohuaData;
@property (nonatomic, retain) NSMutableArray *taohuaData2;
@property (nonatomic, retain) NSMutableArray *arrayData;
@property (nonatomic) int page;
@property (nonatomic) int type;
@end

@implementation PUCategoryVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = false;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"分类";
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.categoryView.titles = @[@"全部",@"川菜",@"点心",@"烘焙",@"家常菜",@"面食",@"粤菜"];
    [self.view addSubview:self.categoryView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    self.collectView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    //          self.collectView.showsHorizontalScrollIndicator = NO;
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    self.collectView.backgroundColor =[UIColor colorWithHex:0xF3F3F3];
    [self.collectView registerClass:PUHomeCell.class forCellWithReuseIdentifier:@"XLHomeCell"];
    [self.view addSubview:self.collectView];
    
    [self.collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.categoryView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    self.arrayData = [PUFoodsModels.shared.list mutableCopy];
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloData) name:@"foodCollcetNotification" object:nil];
}

-(void)reloData{
    [self.collectView reloadData];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PUFoodModel *model=self.taohuaData[indexPath.row];
    static NSString *identifier = @"XLHomeCell";
    PUHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.delegate=self;
//    cell.model=model;
    cell.taohuaModel=model;
    return cell;
    
}
-(void)noLogin{
    PUPhoneLogin *vc=[[PUPhoneLogin alloc]init];
    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
    navVc.modalPresentationStyle=0;
    [self presentViewController:navVc animated:NO completion:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.taohuaData.count;
}
- (CGFloat)minimumInteritemSpacing {
    return 0;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((collectionView.frame.size.width-30)/2,(collectionView.frame.size.width-30)/2*1.52);
}

//计算有行距的文本的文本高度
-(CGFloat)getSpaceLabelHeight:(NSString *)str withAttrDict:(NSMutableDictionary *)dict withWidth:(CGFloat)width {
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size.height;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);//分别为上、左、下、右
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PUFoodModel *model=self.taohuaData[indexPath.row];
    PUFoodDetailsVC *vc = [[PUFoodDetailsVC alloc]init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:true];
}

-(void)loadData{
    if (self.categoryView.selectedIndex == 0) {
        NSMutableArray *array = [NSMutableArray array];
        for (PUFoodsModel *model in self.arrayData) {
            [array addObjectsFromArray:model.foods];
        }
        self.taohuaData = array;
    }
    else {
        PUFoodsModel *model = self.arrayData[self.categoryView.selectedIndex-1];
        self.taohuaData= [model.foods mutableCopy];
    }
    self.page=1;
    [self loadRecommendData];
}

-(NSMutableArray*)getRandomArrFrome:(NSArray*)arr
{
    NSMutableArray *newArr = [NSMutableArray new];
    while (newArr.count != arr.count) {
        //生成随机数
        int x =arc4random() % arr.count;
        id obj = arr[x];
        if (![newArr containsObject:obj]) {
            [newArr addObject:obj];
        }
    }
    return newArr;
}

-(void)loadRecommendData{
    NSDictionary *param =@{
                            @"page":@"1",
                            @"birth":@"1",
//                            @"type":@(self.type)
                            @"type":@(0)
                           };
//    NSString *path=@"/user_recommend";
    NSString *path=@"/tourist/recommend";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        [SVProgressHUD dismiss];
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            self.recommendData= [PUCityListModel mj_objectArrayWithKeyValuesArray:dic[@"list"]];
            NSLog(@"%@",self.recommendData);
            NSMutableArray *array=[NSMutableArray array];

            for (int i=0; i<self.recommendData.count; i++) {
                if (i>=self.taohuaData.count) {
                    break;
                }
                PUFoodModel *model1=self.taohuaData[i];
                PUCityListModel *model2=self.recommendData[i];
                if (model1.userid == nil) {
                    model1.userid=[NSString stringWithFormat:@"%d",model2.ID];
                    model1.username=model2.nickname;
                    model1.userimage=model2.avatar;
                }
                
                [array addObject:model1];
            }
            
          
            self.taohuaData=array;
            if (self.recommendData.count >0) {
                self.collectView.mj_footer.hidden = NO;
            }
            if (self.taohuaData.count==16) {
                self.collectView.mj_footer.hidden = YES;
            }
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
        }
        [self addEmptyData];
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
        [SVProgressHUD dismiss];
        if (self.recommendData.count == 0) {
            self.collectView.mj_footer.hidden = YES;
        }
        [self addEmptyData];
    }];
}
-(void)loadMoreRecommendData{
    NSDictionary *param =@{
                            @"page":[NSString stringWithFormat:@"%d",(int)++self.page],
                            @"birth":@"1",
//                            @"type":@(self.type)
                            @"type":@(0)
                           };
//    NSString *path=@"/user_recommend";
    NSString *path=@"/tourist/recommend";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            
            NSArray *array = [PUCityListModel mj_objectArrayWithKeyValuesArray:dic[@"list"]];
            [self.recommendData addObjectsFromArray:array];
            
            NSMutableArray *array2=[NSMutableArray array];
            for (int i=0; i<self.recommendData.count; i++) {
                if (i>=self.taohuaData2.count) {
                    break;
                }
                PUFoodModel *model1=self.taohuaData2[i];
                PUCityListModel *model2=self.recommendData[i];
                if (model1.userid == nil) {
                    model1.userid=[NSString stringWithFormat:@"%d",model2.ID];
                    model1.username=model2.nickname;
                    model1.userimage=model2.avatar;
                }
                [array2 addObject:model1];

            }
           
            self.taohuaData=array2;
            if (array.count == 0) {
                self.collectView.mj_footer.hidden = YES;
            }
            if (self.taohuaData.count==16) {
                self.collectView.mj_footer.hidden = YES;
            }
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
        }
        [self.collectView.mj_footer endRefreshing];
        [self.collectView reloadData];
       
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
        [self.collectView.mj_footer endRefreshing];
    }];
}

-(void)addEmptyData{
    [self.collectView.mj_header endRefreshing];
  
    self.collectView.configuer.emptyType =  ( self.recommendData.count == 0) ? DznEmptyDataTypeSuccess : DznEmptyDataTypeDefault;
//        self.tableView.configuer.emptyType =  DznEmptyDataTypeSuccess;
    [self.collectView reloadData];
}

-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    [self loadData];
}

- (JXCategoryTitleView *)categoryView {
    if (!_categoryView) {
        _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, _window_width, kBaseSegmentHeight)];
        _categoryView.titleFont = [UIFont systemFontOfSize:16.0f];
        _categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:16];
        _categoryView.titleColor = [UIColor blackColor];
        _categoryView.titleSelectedColor = [UIColor blackColor];
        _categoryView.defaultSelectedIndex = self.meunIndex;
        _categoryView.delegate = self;
       
        JXCategoryIndicatorLineView *lineView = [JXCategoryIndicatorLineView new];
        lineView.lineStyle = JXCategoryIndicatorLineStyle_Normal;
//        lineView.indicatorHeight = ADAPTATIONRATIO * 4.0f;
//        lineView.verticalMargin = ADAPTATIONRATIO * 2.0f;
        
        lineView.indicatorHeight =2.0f;
//        lineView.verticalMargin = 2.0f;
        lineView.indicatorColor=[UIColor blackColor];
        _categoryView.indicators = @[lineView];
    }
    return _categoryView;
}

@end
